﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.DAO;
using ClassLibrary.Entity;
using System.Collections.Generic;

public partial class Admin_UserControl_newpurchase : System.Web.UI.UserControl
{
    TblProductsDAO productDAO = new TblProductsDAO(Global.CONNECTION_STRING);
    TblCustomersDAO cusDAO = new TblCustomersDAO(Global.CONNECTION_STRING);
    TblBookingDAO orderdao = new TblBookingDAO(Global.CONNECTION_STRING);
    TblPhoneBranDAO BrandDAO = new TblPhoneBranDAO(Global.CONNECTION_STRING);
    TblModelDAO modelDAO = new TblModelDAO(Global.CONNECTION_STRING);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadProduct_ByModelFac();
           
            LoadFactory();
            LoadSale();
            string id = Request.QueryString["id"];
            string idB = Request.QueryString["idB"];
            if (id != "" || id != null && idB !=null)
            {
                LoadDetail();
                hypInvice.NavigateUrl = "~/Admin/Report_Purchase.aspx?idCus=" + Global.ConvertToInt(id);
                txtCompany.Enabled = false;
                txtContact.Enabled = false;
                txtCustomername.Enabled = false;
                txt_ExtPrice.Enabled = false;
                txtGst.Enabled = false;
               // txtItemNo.Enabled = false;
               // txtQuantity.Enabled = false;
                txt_UnitPrice.Enabled = false;
                txtDate.Enabled = false;
              //  txtivoiceNo.Enabled = false;
             //   txtsaleid.Enabled = false;
              //  cbProduct.Enabled = false;
            }

            txtCompany.Enabled = true;
            txtContact.Enabled = true;
            txtCustomername.Enabled = true;
            txt_ExtPrice.Enabled = true;
            txtGst.Enabled = true;
          //  txtItemNo.Enabled = true;
            //txtQuantity.Enabled = true;
            txt_UnitPrice.Enabled = true;
            txtDate.Enabled = true;
           // txtivoiceNo.Enabled = true;
           // txtsaleid.Enabled = true;
           // cbProduct.Enabled = true;

        }
    }

    // Load Manufactory

    private void LoadFactory()
    {
        idManufactory.DataSource = BrandDAO.GetAll();
        idManufactory.DataValueField = "IDBrand";
        idManufactory.DataTextField = "BrandName";
        idManufactory.DataBind();
        ListItem item = new ListItem("---- Select Brand ---", "");
        idManufactory.Items.Insert(0, item);
    }
    // load sale rep
    private void LoadSale()
    {
        drSaleRep.DataSource = cusDAO.GetStaffList(1);
        drSaleRep.DataTextField = "CustomerFirstname";
        drSaleRep.DataValueField = "CustomerIndex";
        drSaleRep.DataBind();
      
    }
    // load product By Model, Factory
    private void LoadProduct_ByModelFac()
    {
        cbProductSell.DataSource = productDAO.GetProductsList_ByID(2, Global.ConvertToInt(drModel.SelectedValue), Global.ConvertToInt(idManufactory.SelectedValue), txtProductType.Text.Trim(),1);
        cbProductSell.DataValueField = "ProductID";
        cbProductSell.DataTextField = "ProductName";
        cbProductSell.DataBind();

        ListItem item = new ListItem("------- Select Product ------", "");
        cbProductSell.Items.Insert(0, item);
    }
   

    // load Detail Purchase 
    private void LoadDetail()
    {
        LoadProduct_ByModelFac();

        string idCus = Request.QueryString["id"];
        DataTable customer = cusDAO.GetCustomerId(Global.ConvertToInt(idCus));
        foreach (DataRow dr in customer.Rows)
        {
            txtCompany.Text = dr["Companyname"].ToString();
            txtContact.Text = dr["phonemobile"].ToString();
            txtCustomername.Text = dr["CustomerFullname"].ToString();
        }
        // noi dung booking
        DataTable dt = orderdao.GetBook_ByIDCustomer(Global.ConvertToInt(idCus));

        foreach (DataRow dr in dt.Rows)
        {

            decimal discount = Convert.ToInt32(dr["Discount"].ToString());
            decimal total = Convert.ToDecimal(dr["Total"].ToString());
            txtGst.Text = discount.ToString("c");
            lbtotalAmount.Text = total.ToString("c");
            TextBox2.Text = dr["IDOrder"].ToString();
          
            txtDate.Text = Convert.ToDateTime(dr["OrderDate"]).ToShortDateString();
         
            txt_ExtPrice.Text = dr["ExtendPrice"].ToString();
            txt_UnitPrice.Text = dr["UnitPrice"].ToString();

        }

        string idB = Request.QueryString["idB"];
        grdShoppingCart.DataSource = orderdao.GetBookByID(Global.ConvertToInt(idB), Convert.ToInt32(idCus));
        grdShoppingCart.DataBind();
    }
    protected void cbProduct_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable product = productDAO.GetProductById(Global.ConvertToInt(cbProductSell.SelectedValue));
        foreach (DataRow dr in product.Rows)
        {
            //RRP: giá bán ra
            txt_UnitPrice.Text = dr["RRP"].ToString();
          //  txtivoiceNo.Text = "1";
           // txtItemNo.Text = dr["ProductID"].ToString();
           // txtsaleid.Text = "1";

        }
    }
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        int Quantity;
        decimal Price;
        decimal TotalPrice;
        Quantity = Global.ConvertToInt(txtQuantity.Text);
        Price = decimal.Parse(txt_UnitPrice.Text);
        TotalPrice = Quantity * Price;
        txt_ExtPrice.Text = TotalPrice.ToString();
        // Tong tien
        //lbtotalAmount.Text = TotalPrice.ToString();

    }
    protected void txtGst_TextChanged(object sender, EventArgs e)
    {
        if (txtGst.Text != "0")
        {
            decimal Total_Price;
            Total_Price = decimal.Parse(lbtotalAmount.Text);

            int GST = 0;
            GST = Global.ConvertToInt(txtGst.Text);
            decimal Total;
            Total = Total_Price - (Total_Price * GST / 100);
            lbtotalAmount.Text = Total.ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        // insert customer
        TblCustomers cus = new TblCustomers();
        cus.CustomerFullname = txtCustomername.Text;
        cus.Companyname = txtCompany.Text;
        cus.Phonemobile = txtContact.Text;
        cus.DateCreated = DateTime.Now;
        cus.IsAdmin = false;
        cus.CustomerTitle = "";
        cus.CustomerFirstname = "";
        cus.CustomerLastname = "";

        cus.Postalnumber = "";
        cus.Postalstreet = "";

        cus.Postalsuburb = "";

        cus.Postalpostcode = "";
        cus.Postalstate = "";
        cus.Phonework = txtContact.Text;
        cus.Phonehome = txtContact.Text;

        cus.Phonefacsimile = "";
        cus.Emailaddress = "";
        //customer.CustomerUsername = txtUsername.Text;
        cus.Emailpassword = "";
        cus.PreferContactMethod = 1;


        cus.CustomerIndex = 0;
        cusDAO.InsUpdCustomers(cus, 1);

        DataTable dt = cusDAO.getCustomer_New();
        int idCus = 0;
        foreach (DataRow dr in dt.Rows)
        {
            idCus = Global.ConvertToInt(dr["CustomerIndex"].ToString());
        }

        //// inset booking
        //TblBooking order = new TblBooking();
        //order.SaleRep = drSaleRep.SelectedItem.Text;
        //order.Status = 0;
        //order.OrderDate = DateTime.Now;
        //order.Total = decimal.Parse(lbtotalAmount.Text);
       
        //int id;
        //orderdao.Insert(order, out id);


        //// insert TblBookingDetail
        //TblBookingDetail bookingDetail = new TblBookingDetail();
        //bookingDetail.IdOrder = id;
        //bookingDetail.ProductId = Global.ConvertToInt(cbProductSell.SelectedValue);
        //bookingDetail.Quantity = Global.ConvertToInt(txtQuantity.Text);
        //bookingDetail.UnitPrice = decimal.Parse(txt_UnitPrice.Text);
        //bookingDetail.ExtendPrice = decimal.Parse(txt_ExtPrice.Text);
        //bookingDetail.Discount = Global.ConvertToInt(txtGst.Text);
        //orderdao.InsertBookingDetail(bookingDetail);


        TblBookingDAO orderdao = new TblBookingDAO(Global.CONNECTION_STRING);
        TblBooking order = new TblBooking();
        order.SaleRep = drSaleRep.SelectedItem.Text;
        order.OrderDate = DateTime.Now;
        //order.ShipTo = "Name: " + " " + txtCustomername.Text + "." + "Contact: " + txtContact.Text;
        order.CustomerIndex = idCus;

        order.Total = decimal.Parse(Session[Global.SESSION_TOTAL].ToString());


        List<TblBookingDetail> arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];
        int id;

        orderdao.Insert(order, arrItems, out id);
        Session[Global.SESSION_CART] = null;
        Session[Global.SESSION_TOTAL] = null;


        Response.Redirect("~/Admin/Purchase.aspx?id=" + idCus);

        LoadData();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/Default.aspx");
    }
    protected void txtItemNo_TextChanged(object sender, EventArgs e)
    {

    }
    protected void idManufactory_SelectedIndexChanged(object sender, EventArgs e)
    {
        drModel.DataSource = modelDAO.GetModelByIdBrand(Global.ConvertToInt(idManufactory.SelectedValue));
        drModel.DataTextField = "Model";
        drModel.DataValueField = "IDModel";
        drModel.DataBind();

        ListItem item = new ListItem("-- Select --", "");
        drModel.Items.Insert(0, item);



        cbProductSell.DataSource = productDAO.GetProductsList_ByID(2,0, Global.ConvertToInt(idManufactory.SelectedValue), "", 3);
        cbProductSell.DataValueField = "ProductID";
        cbProductSell.DataTextField = "ProductName";
        cbProductSell.DataBind();
        ListItem item1 = new ListItem("------- Select Product ------", "");
        cbProductSell.Items.Insert(0, item1);
        

    }
    protected void cbProductSell_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable product = productDAO.GetProductById(Global.ConvertToInt(cbProductSell.SelectedValue));
        foreach (DataRow dr in product.Rows)
        {
            //RRP: giá bán ra
            txt_UnitPrice.Text = dr["RRP"].ToString();
        

        }
    }
    protected void drModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadProduct_ByModelFac();
    }
    protected void txtProductType_TextChanged(object sender, EventArgs e)
    {
        cbProductSell.DataSource = productDAO.GetProductsList_ByID(2, Global.ConvertToInt(drModel.SelectedValue), Global.ConvertToInt(idManufactory.SelectedValue), txtProductType.Text.Trim(), 2);
        cbProductSell.DataValueField = "ProductID";
        cbProductSell.DataTextField = "ProductName";
        cbProductSell.DataBind();

        ListItem item = new ListItem("------- Select Product ------", "");
        cbProductSell.Items.Insert(0, item);
    }

    // Load Shopping CArt

    private void LoadData()
    {
        int iNoOfItems = LoadCart();
        decimal dTotalAmount = SetTotalAmount();
        ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("c") + "');", true);
    }

    protected void insert_Click(object sender, ImageClickEventArgs e)
    {
        bool flag = false;
        try
        {         
           // string id = Request.QueryString["id"];
            string id = cbProductSell.SelectedValue;
            Session[Global.SL] = txtQuantity.Text;
            BasePage.SetShoppingCartSesstion(id + "|0");

            List<TblBookingDetail> arrItems = new List<TblBookingDetail>();
            if (Session[Global.SESSION_CART] != null)
                arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];

            int iNoOfItems = 0;
            decimal dTotalAmount = 0;

            foreach (TblBookingDetail order in arrItems)
            {
                iNoOfItems += order.Quantity;
                dTotalAmount += Convert.ToDecimal(order.Quantity) * Convert.ToDecimal(order.UnitPrice);

            }
           
            ScriptManager.RegisterStartupScript(insert,
                this.insert.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("c") + "');", true);
            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
        if(flag)
        {
            LoadData();
            txtQuantity.Text = txtProductType.Text = txt_UnitPrice.Text = txt_ExtPrice.Text = string.Empty;
        }
    }
    protected void imgDelete_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            ImageButton imgDel = (ImageButton)sender;
            if (imgDel != null)
            {
                string strUniqueID = imgDel.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[4].Replace("ctl", "")) - 2);

                if (Session[Global.SESSION_CART] != null)
                {
                    List<TblBookingDetail> arrProducts = (List<TblBookingDetail>)Session[Global.SESSION_CART];                   
                    arrProducts.RemoveAt(iRowIndex);
                    int iNoOfItems = LoadCart();
                    decimal dTotalAmount = SetTotalAmount();

                    ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("c") + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
    }
    protected void grdShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            GridViewRow gridViewRow = e.Row;
         
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    private int LoadCart()
    {
        try
        {
            //ArrayList arrItems = (ArrayList)Session[Global.SESSION_CART];

            List<TblBookingDetail> arrItems = new List<TblBookingDetail>();
            if (Session[Global.SESSION_CART] != null)
                arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];

            int iNoOfItems = 0;
            decimal dTotalAmount = 0;

            foreach (TblBookingDetail order in arrItems)
            {
                iNoOfItems += order.Quantity;         
                dTotalAmount += order.Quantity * order.UnitPrice;
            }

            grdShoppingCart.DataSource = arrItems;
            grdShoppingCart.DataBind();

            return iNoOfItems;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private decimal SetTotalAmount()
    {
        try
        {
            decimal dTotalAmount = 0;
            for (int i = 0; i < grdShoppingCart.Rows.Count; i++)
            {
                Label lblSubTotal = (Label)grdShoppingCart.Rows[i].Cells[3].FindControl("lblSubTotal");
                Label lblPrice = (Label)grdShoppingCart.Rows[i].Cells[1].FindControl("lblPrice");
                Label txtQuantity = (Label)grdShoppingCart.Rows[i].Cells[2].FindControl("txtQuantity");
                Label lblMatchedPrice = (Label)grdShoppingCart.Rows[i].Cells[1].FindControl("lblMatchedPrice");
                double dPrice = 0;
                double dMatchedPrice = 0;
                int iQuantity = 0;
                try
                {
                    dPrice = Convert.ToDouble(lblPrice.Text.Trim().Replace("$", ""));
                    dMatchedPrice = Convert.ToDouble(lblMatchedPrice.Text.Trim().Replace("$", ""));
                    iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
                }
                catch (Exception) { }
                double dSubTotal = 0;

                lblPrice.Text = dPrice.ToString("c");
                if (dMatchedPrice == 0)
                {
                    dSubTotal = dPrice * iQuantity;
                    lblPrice.Text = dPrice.ToString("c");
                    lblMatchedPrice.Visible = false;
                }
                else
                {
                    dSubTotal = dMatchedPrice * iQuantity;
                    lblPrice.CssClass = "clsPriceCartCrossed";
                    lblMatchedPrice.Text = "\r\n" + dMatchedPrice.ToString("c");
                    lblMatchedPrice.Visible = true;
                }

                lblSubTotal.Text = dSubTotal.ToString("c");

                if (lblSubTotal != null)
                {
                    try
                    {
                        dTotalAmount += Convert.ToDecimal(lblSubTotal.Text.Trim().Replace("$", ""));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                lbtotalAmount.Text = dTotalAmount.ToString("c");

            }

            Session[Global.SESSION_TOTAL] = dTotalAmount;

            return dTotalAmount;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

   
}
